package com.seckill.service.impl;

import com.seckill.entity.Result;
import com.seckill.enums.SeckillStatEnum;
import com.seckill.mapper.SeckillMapper;
import com.seckill.mapper.SuccessKilledMapper;
import com.seckill.model.Seckill;
import com.seckill.model.SuccessKilled;
import com.seckill.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

/**
 * @Author: hualao
 * @Version: 0.0.1V
 * @Date: 2019/1/24
 * @Description: 秒杀商品信息
 **/
@Service
public class SeckillServiceImpl implements SeckillService{

    @Autowired
    private SeckillMapper seckillMapper;

    @Autowired
    private SuccessKilledMapper successKilledMapper;

    @Override
    @Transactional
    public Result startSeckil(long seckillId, long userId) {
        //查询秒杀商品库存
        Integer number = seckillMapper.numberByseckillId(seckillId);
        if(number<=0){
            return Result.error(SeckillStatEnum.END.getInfo());
        }
        //减库存
        seckillMapper.subtractNumber(seckillId);
        //生成秒杀成功信息
        SuccessKilled successKilled = new SuccessKilled();
        successKilled.setSeckillId(seckillId);
        successKilled.setUserId(userId);
        successKilled.setState((short) 0);
        successKilled.setCreateTime(new Timestamp(System.currentTimeMillis()));
        successKilledMapper.insert(successKilled);
        return Result.ok(SeckillStatEnum.SUCCESS.getInfo());
    }

    @Override
    public void initNumberBySeckillId(long seckillId) {
        Seckill seckill = new Seckill();
        seckill.setNumber(100);
        seckill.setSeckillId(seckillId);
        seckillMapper.updateByPrimaryKeySelective(seckill);
    }

}
